//
//  BZUCForgetV.m
//  Pods
//
//  Created by quheng on 2017/8/29.
//
//

#import "BZUCForgetV.h"
#import "BZUCInputV.h"
#import <Masonry/Masonry.h>
#import "NSString+NormalRegex.h"
#import "BZUCLoginService.h"
#import <libextobjc/EXTScope.h>
#import <YYKit/NSString+YYAdd.h>
#import "UIView+ViewController.h"
#import "BZUCCurrentUser.h"
#import <AFNetworking/AFNetworking.h>
#import <BZBaseWidget/BZBaseWidget.h>

@interface BZUCForgetV()<BZUCInputVDelegate>

@property (nonatomic, strong) BZUCLoginService *loginService;

@end

@implementation BZUCForgetV


- (instancetype)init{
    
    self = [super init];
    
    if (self) {
        
        [self configureV];
    }
    return self;
}

- (void)configureV{
    
    
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:4];
    
    for (NSUInteger i = 0; i<4; i++) {
        
        BZUCInputV *inputV = [[BZUCInputV alloc]init];
        inputV.index = i;
        inputV.delegate = self;
        [self addSubview:inputV];
        [inputV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).with.offset(16);
            make.right.equalTo(self).with.offset(-16);
            make.top.equalTo(self).with.offset(44*i+30);
            make.height.mas_offset(44);
        }];
        [arr addObject:inputV];
    }
    
    self.inputArr = [arr copy];
    
    UIButton *finishBtn = [[UIButton alloc]init];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn addTarget:self action:@selector(clickFinishBtn:) forControlEvents:UIControlEventTouchUpInside];
    [finishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [finishBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    finishBtn.layer.cornerRadius  = 8;
    finishBtn.layer.masksToBounds = YES;
    finishBtn.backgroundColor = [UIColor colorWithRed:1.00 green:0.42 blue:0.12 alpha:1.00];
    [self addSubview:finishBtn];
    self.finishBtn = finishBtn;
    
    [finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).with.offset(44*4+30+40);
        make.left.equalTo(self).with.offset(58);
        make.right.equalTo(self).with.offset(-58);
        make.height.mas_offset(36);//暂时设为0，不用
    }];
    
}



- (void)clickFinishBtn:(UIButton *)sender{

    
    
    [self endEditing:YES];
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusNotReachable) {
        [MBProgressHUD showClueInView:self title:@"无网络" duration:0.75];
        return;
    }

    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:4];
    
    NSString *oldPassword = @"";
    
    
    for (NSUInteger i = 0; i < 4; i++) {
        
        BZUCInputV *inputV = self.inputArr[i];
        [inputV.textF resignFirstResponder];
        inputV.textF.text = [inputV.textF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (![inputV.textF.text length]) {
            
            if (i == 0) {
                [MBProgressHUD showClueInView:self title:@"请输入手机号" duration:0.7];
                break;
            }else if (i == 1){
                [MBProgressHUD showClueInView:self title:@"请输入验证码" duration:0.7];
                break;
            }else if (i == 2){
                [MBProgressHUD showClueInView:self title:@"密码未填写" duration:0.7];
                break;
            }else if (i == 3){
                [MBProgressHUD showClueInView:self title:@"密码未填写" duration:0.7];
                break;
            }
        }else{
            if (i == 0) {
                if (![NSString isValidateMobile:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"手机号输入有误" duration:0.7];
                    break;
                }
                [param setObject:inputV.textF.text forKey:@"phone"];
            }else if (i == 1){
                if ([inputV.textF.text length] < 6) {
                    [MBProgressHUD showClueInView:self title:@"验证码为6位数" duration:0.7];
                    break;
                }
                [param setObject:inputV.textF.text forKey:@"code"];
            }else if (i == 2){
                if (![NSString isValidatePassword:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"密码为6~20位字母、数字、点、下划线、减号组合" duration:0.7];
                    break;
                }else{
                    oldPassword = inputV.textF.text;
                }
            }else if (i == 3){
                if (![oldPassword isEqualToString:inputV.textF.text]) {
                    [MBProgressHUD showClueInView:self title:@"两次密码输入不一致" duration:0.7];
                    break;
                }else{
                    [param setObject:inputV.textF.text  forKey:@"password"];
                }
            }
        }

    }
    
    if ([param count] < 3) {
        
        return;
    }
    
    @weakify(self);
    
    [self.loginService checkSMSCodeOfPhone:[param objectForKey:@"phone"]
                                   smsCode:[param objectForKey:@"code"]
                                   success:^(NSString *code, id responseObject) {
                                       
                                       @strongify(self);
                                       
                                       [self.loginService resetPasswordWithNewPassword:[[param objectForKey:@"password"] md5String]
                                                                                 phone:[param objectForKey:@"phone"]
                                                                               success:^(NSString *code, id responseObject) {
                                                                                   
                                                                                   BZUCUserModel *currentUser = [[BZUCUserModel alloc]init];
                                                                                   currentUser.phone = [param objectForKey:@"phone"];
                                                                                   currentUser.password = [param objectForKey:@"password"];
                                                                                   [[BZUCCurrentUser shareInstance]setUserModel:currentUser];
                                                                                   
                                                                                   [MBProgressHUD showClueInView:self title:@"密码修改成功" duration:0.75];
                                                                                   
                                                                                   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                                                                       
                                                                                       [[self viewController].navigationController popViewControllerAnimated:YES];
                                                                                   });
                                           
                                       } failure:^(NSString *code, NSError *error) {
                                           
                                           
                                       }];
                                       
        
    } failure:^(NSString *code, NSError *error) {
        
    }];
    
}



- (BZUCLoginService *)loginService{

    if (!_loginService) {
        
        _loginService = [[BZUCLoginService alloc]init];
    }

    return _loginService;
}


- (void)shouldTriggerTimeKeeper:(BZUCInputV *)inputView timeKeeper:(BZBaseTimeKeeperBtn *)timeKeeper{
    
    BZUCInputV *inputV = self.inputArr[0];
    inputV.textF.text = [inputV.textF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (![inputV.textF.text length]) {
        [MBProgressHUD showClueInView:self title:@"请输入手机号" duration:0.7];
        return;
    }
    if (![NSString isValidateMobile:inputV.textF.text]) {
        [MBProgressHUD showClueInView:self title:@"手机号输入有误" duration:0.7];
        return;
    }
    
    
    @weakify(self);
    [self.loginService checkoutUserName:inputV.textF.text
                           success:^(NSString *code, id responseObject) {
                               
                               @strongify(self);
                               
                               __block BOOL shouldTrigger = NO;
                               
                               [self.loginService findSMSCodeOfPhone:inputV.textF.text
                                                            withImei:[inputV.textF.text md5String]
                                                            withCode:2
                                                             success:^(NSString *code, id responseObject) {
//                                   [timeKeeper stopTimers];
                                                                 
                                                                 

                                                                 
                               } failure:^(NSString *code, NSError *error) {
                                   
                                   if ([[error.userInfo objectForKey:NSLocalizedDescriptionKey] containsString:@"无网络"] || [[error.userInfo objectForKey:NSLocalizedDescriptionKey] containsString:@"短信发送次数超过限制"]) {
                                       shouldTrigger = YES;
                                       [timeKeeper stopTimers];
                                   }

                               }];
                               
                               if (!shouldTrigger) {
                                   [timeKeeper beginTimers];
                               }

    } failure:^(NSString *code, NSError *error) {
        
    }];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self endEditing:YES];

}


@end
